﻿/*******************************************************************************
 * AAEngine
 * Copyright (c) 2010 Mike Jarosch
 *
 * Original source PushButton Engine:
 * Copyright (C) 2009 PushButton Labs, LLC
 * For more information see http://www.pushbuttonengine.com
 *
 * This file is licensed under the terms of the MIT license, which is included
 * in the "MIT License.txt" file at the root directory of this SDK.
 ******************************************************************************/

using System;
using Microsoft.Xna.Framework;
using AAEngine.Engine;
using AAEngine.Engine.Debug;

namespace AAEngine.Rendering2D.SpriteSheet
{
    public class CellCountDivider : ISpriteSheetDivider
    {
        private int _xCount, _yCount;
        private SpriteSheetComponent _owningSheet;

        public int XCount
        {
            get { return _xCount; }
            set { _xCount = value; }
        }

        public int YCount
        {
            get { return _yCount; }
            set { _yCount = value; }
        }

        public SpriteSheetComponent OwningSheet
        {
            set
            {
                if (_owningSheet != null)
                {
                    Logger.Warn(this, "OwningSheet", "Already assigned to a sheet, reassigning may result in unexpected behavior.");
                }
                _owningSheet = value;
            }
        }

        public int FrameCount
        {
            get { return _xCount * _yCount; }
        }

        public Rectangle FrameArea(int index)
        {
            if (_owningSheet == null)
            {
                throw new AAException("OwningSheet must be set before calling this!");
            }

            int imageWidth = _owningSheet.ImageData.Width;
            int imageHeight = _owningSheet.ImageData.Height;

            int width = imageWidth / _xCount;
            int height = imageHeight / _yCount;

            int x = index % _xCount;
            int y = (int)Math.Floor((double)(index / _xCount));

            int startX = x * width;
            int startY = y * height;

            return new Rectangle(startX, startY, width, height);
        }

        public ISpriteSheetDivider Clone()
        {
            CellCountDivider c = new CellCountDivider();
            c.XCount = _xCount;
            c.YCount = _yCount;
            return c;
        }
    }
}
